import DatePicker from "components/antd-compatible/date-picker";
/**
 * Created by tanbingqin on 2020/7/17.
 */
import { messages, queryCurrencyPrecision, getQueryUrlParam } from "share/common";
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux';
import moment from "moment";
import {  Icon, Popover, Spin, Popconfirm, message, Tag, Row, Col, Alert } from "antd";
import Condition from "components/condition";
const { If } = Condition;
import constants from "share/constants";
import travelUtil from 'containers/request/travel-request/travelUtil'
import ApprovingEdit from 'containers/approve/approving-edit'
import QrCode from "qrcode.react";
import RelatedShowList from 'containers/request/related-show-list'
import menuRoute from 'routes/menuRoute'
import TravelPreviousVersion from 'containers/request/travel-request/travel-previous-version'

class SlideApplicationHeader extends Component {
  constructor(props) {
    super(props);
    this.state = {
      financeLoanDetail: menuRoute.getRouteItem('loan-detail-view','key'), //财务查看的借款单详情页
      loanDetail: menuRoute.getRouteItem('loan-detail','key'), //借款单详情页
      editLoan: menuRoute.getRouteItem('edit-borrow','key'), //单行借款单编辑页
      loanEditDetail: menuRoute.getRouteItem('loan-detail','key'), //多行借款单编辑页，单行&多行非编辑详情页
    }
  }

  renderCloseDate = () => {
    const { info } = this.context;
    let closeDate = null; //（预计）停用日期
    if (info.status === 1003) { //已通过状态停用时间都是获取个人的停用时间
      if (info.applicationParticipant && info.applicationParticipant.closeDate) {
        if (info.applicationParticipant.closed === 1) { //当前单据对于当前操作人是已停用状态
          closeDate = (
            <span>
              {messages('request-1.key3')/*关闭日期*/}：
              {moment(info.applicationParticipant.closeDate).format('YYYY-MM-DD')}
            </span>
          )
        } else {
          //在对于人员未关闭时是否显示停用日期以是否有个人的停用日期为准，停用日期一直获取的为个人的停用日期
          closeDate = (
            <span>
              {messages('request-1.key4')/*预计关闭日期*/}：
              {moment(info.applicationParticipant.closeDate).format('YYYY-MM-DD')}
            </span>
          )
        }
      }
    } else { //不是已通过状态时，停用时间都是获取的是单据的停用时间，根据单子的属性
      if (info.closeEnabled && info.closeDate) {
        closeDate = (
          <span>
            {messages('request-1.key4')/*预计关闭日期*/}：
            {moment(info.closeDate).format('YYYY-MM-DD')}
          </span>
        )
      }
    }
    return closeDate;
  };

  renderWarningList = () => {
    const { info } = this.context;
    let warningList = info.warningList ? JSON.parse(info.warningList) : null;
    if (warningList) {
      return (
        warningList.map((warning, index) => (
          <Alert
            message={warning.title}
            description={warning.message ? travelUtil.renderMessage(warning.message) : '--'}
            banner
            type={warning.type === 0 ? 'warning' : 'error'}
            style={{marginBottom: 12}}
            key={index}
          />
        ))
      )
    } else {
      return null;
    }
  };

  renderThirdInfo = () => {
    const { thirdPartyInfo } = this.context;
    if (thirdPartyInfo.code === 'SUCCESS' && thirdPartyInfo.body) {
      return (
        <Alert
          style={{marginBottom: 12, whiteSpace: 'pre-wrap'}}
          message={thirdPartyInfo.body}
          type="info"
          showIcon
        />
      )
    } else {
      return null;
    }
  };

  //预览表单二维码
  renderPreviewQCode = () => {
    const { info } = this.context;
    let applicationOID = info.applicationOID;
    let qrcodeValue = `https://www.huilianyi.com/miniprogram/?applicationOID=${applicationOID}&baseURL=${window.location.origin}`;
    return (
      <div>
        <div style={{textAlign: "center", marginBottom: 6}}>{messages('request-1.key2')/*微信扫一扫转发*/}</div>
        <QrCode
          value={qrcodeValue}
          renderAs={"svg"}
          fgColor={"#000000"}
          size={100}
        />
      </div>
    )
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { info } = this.context;
    let showHangUp = false;
    let approverOID = this.props.approverOID;
    info.approvalChains && info.approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  //去借款功能的点击关联借款的单据的跳转
  goAutoLoan = () => {
    const { isEdit, costApplication } = this.props;
    const { loanDetail, financeLoanDetail, editLoan, loanEditDetail } = this.state;
    const { info } = this.context;
    let applicationOID = info.applicationOID;
    let loanBillOID = info && info.loanBillOID;
    let loanFormOID = info && info.loanBill && info.loanBill.formOID;
    let loanStatus = info && info.loanBill && info.loanBill.status;
    let loanFormType = info && info.loanBill && info.loanBill.type;
    if (loanStatus === 1010) {
      message.error(messages('request-1.key174')/*未找到借款单，单据可能已被删除。*/);
      return;
    }
    if (isEdit) {
      let url = '';
      if (loanFormType === 2005) {
        //单行借款单编辑页
        url = editLoan.url.replace(':formOID', loanFormOID).replace(':loanBillOID', loanBillOID).replace(':applicationOID', applicationOID);
      } else {
        //多行借款单编辑页
        url = loanEditDetail.url.replace(':formOID', loanFormOID).replace(':loanBillOID', loanBillOID).replace(':applicationOID', applicationOID);
      }
      this.context.router.push(url);
    } else {
      let url = !!costApplication ? financeLoanDetail.url : loanDetail.url;
      url = url.replace(':formOID', loanFormOID).replace(':loanBillOID', loanBillOID).replace(':applicationOID', applicationOID) + '?from=request';
      if (window.ISIE9) {
        url = `#${url}`;
      }
      window.open(url);
    }
  };

  render() {
    const { info, applicant, refreshInfo, form: formInfo } = this.context;
    const { isCheckEdit, approverOID, isEdit, costApplication, quotaObj, isPreVersion } = this.props;
    let custFormValues = info.custFormValues || []; //自定义表单
    custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
    const showQrCode = info.status === 1002 && formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['travel.application.share.image'] && JSON.parse(formInfo.customFormPropertyMap['travel.application.share.image']).enabled;
    let qrCode = <div style={{position: "absolute", right: 0, top: '-9px', zIndex: 3, fontSize: 25, cursor: "pointer"}}>
      <Popover
        content={this.renderPreviewQCode()}
        trigger="click"
        placement="left"
        getPopupContainer={(triggerNode) => triggerNode.parentNode}
      >
        <Icon type="qrcode" />
      </Popover>
    </div>;
    let loanCurrencyCode = info && info.loanBillOID && info.loanBill.currencyCode;
    let loanCurrencyAmount = info && info.loanBillOID && info.loanBill.currencyAmount;
    let loanBusinessCode = info && info.loanBillOID && info.loanBill.businessCode;
    return (
      <div>
        {this.renderWarningList()}
        {this.renderThirdInfo()}
        {!isEdit && (
          <Row className="margin-bottom-12">
            <span className="detail-info">
              {messages('common.submit.date')/*提交日期*/}：{moment(info.submittedDate).format('YYYY-MM-DD')}，
              {messages('common.document.code')/*单号*/}：{info.businessCode}
            </span>
          </Row>
        )}
        <Row className="margin-bottom-12">
          <span className="detail-info">
            {messages('request-1.key9')/*当前状态*/}：
            {(info.closed || info.participantClosed || (info.applicationParticipant && info.applicationParticipant.closed === 1)) ?
              messages('request-1.key10')/*已关闭*/ : (
                (!isEdit && constants.getTextByValue(String(info.status + '' + info.type), 'documentStatus')) ||
                constants.getTextByValue(String(info.status + '' + info.rejectType), 'documentStatus') ||
                constants.getTextByValue(String(info.status), 'documentStatus')
              )
            }
            {this.renderCloseDate() && (
              <span>
                ，{this.renderCloseDate()}
              </span>
            )}
          </span>
        </Row>
        {info.uniformReimbursementClerk && (
          <Row className="margin-bottom-12">
            <span className="detail-info">
              {messages('request-1.key11')/*已转交*/}：{info.uniformReimbursementClerk.fullName}
            </span>
          </Row>
        )}
        {info.version > 0 && (
          <Row className="margin-bottom-12">
            <TravelPreviousVersion info={info} isPreVersion={isPreVersion}/>
          </Row>
        )}
        <Row className="margin-bottom-12">
          <span className="form-title">{info.formName}</span>
          {isCheckEdit && (
            <ApprovingEdit
              approvalOID={approverOID || getQueryUrlParam('approverOID')}
              entityOID={info.applicationOID}
              formOID={info.formOID}
              entityType={1001}
              custFormValues={custFormValues}
              handleAfterSave={refreshInfo}
            />
          )}
          {showQrCode && qrCode}
        </Row>
        <Row className="margin-bottom-12">
          <span className="form-title">
            {info.currencyCode}&nbsp;&nbsp;
            {this.filterMoney(info.totalAmount || 0, queryCurrencyPrecision(info.currencyCode), true)}
          </span>
        </Row>
        <Row className={!isEdit && this.isShowHangUp() ? "margin-bottom-12" : ""}>
          {!isEdit && this.isShowHangUp() && (
            <Tag color="#505564">{messages('request-1.key12')/*暂挂*/}</Tag>
          )}
        </Row>
        {info && info.loanBillOID && (
          <div className="margin-bottom-12 info-block">
            <div>
              <span className="info-label">{messages('request-1.key818')/*借款金额：*/}</span>
              <span className="info-amount">
                {loanCurrencyCode}&nbsp;
                {React.Component.prototype.filterMoney(loanCurrencyAmount, queryCurrencyPrecision(loanCurrencyCode), true)}
              </span>
            </div>
            <div>
              <span className="info-label">{messages('request-1.key819')/*借款单号：*/}</span>
              <span className="info-link" onClick={this.goAutoLoan}>
                {loanBusinessCode}&nbsp;<Icon type="right" />
              </span>
            </div>
          </div>
        )}
        {quotaObj && quotaObj.takeQuota && (
          <div className="margin-bottom-12 info-block">
            <div>
              <span className="info-label">{messages('request-1.key820')/*申请金额：*/}</span>
              <span className="info-amount">
                CNY&nbsp;
                {React.Component.prototype.filterMoney(quotaObj.quotaAmount, 2, true)}
              </span>
              &nbsp;&nbsp;&nbsp;
              {!isEdit && info.quotaStatus === 1001 && (<span className="quota-tag-1">{messages('request-1.key18')/*待发放*/}</span>)}
              {!isEdit && info.quotaStatus === 1002 && (<span className="quota-tag-2">{messages('request-1.key19')/*已发放*/}</span>)}
              {!isEdit && info.quotaStatus === 1003 && (<span className="quota-tag-3">{messages('request-1.key20')/*发放失败*/}</span>)}
            </div>
            <div>
              <span className="info-label">{messages('request-1.key265')/*额度发放至：*/}</span>
              <span className="info-label">
                {quotaObj.quotaBankCardDTO && (
                  <span>
                    {quotaObj.quotaBankCardDTO.paymentRemark === '002' ? messages('request-1.key15')/*瑞贝卡*/ : messages('request-1.key16')/*领创A卡*/}
                  </span>
                )}
                {quotaObj.quotaBankCardDTO && quotaObj.quotaBankCardDTO.bankAccountNo && quotaObj.quotaBankCardDTO.bankAccountNo.substr(-4)}
              </span>
            </div>
          </div>
        )}
        {!isEdit && <RelatedShowList info={info} alreadyHas={!!costApplication} isFinance={!!costApplication} />}
      </div>
    )
  }
}

SlideApplicationHeader.propTypes = {
  isCheckEdit: PropTypes.bool, //是否要处理审批中编辑
  approverOID: PropTypes.string,
  isEdit: PropTypes.bool, //是否是单据编辑状态的头部
  costApplication: PropTypes.bool, //是否是财务查看进来的
  quotaObj: PropTypes.object, //额度相关字段
  isPreVersion: React.PropTypes.string, //是否是已变更的前一版
};

SlideApplicationHeader.contextTypes = {
  applicant: PropTypes.object,
  form: PropTypes.object,
  info: PropTypes.object,
  jobInfo: PropTypes.object,
  refreshInfo: PropTypes.func,
  thirdPartyInfo: PropTypes.object,
  router: PropTypes.object,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(SlideApplicationHeader)
